package com.hnld.transform.handler.impl;

import cn.hutool.core.io.FileUtil;
import com.google.common.collect.Maps;
import com.hnld.transform.cosntant.TransformConstant;
import com.hnld.transform.dictionary.Directory;
import com.hnld.transform.entity.Parameter;
import com.hnld.transform.enums.FileTypeEnum;
import com.hnld.transform.handler.ITypeHandler;
import com.hnld.transform.util.FileTransferUtil;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

public class ImageHandler implements ITypeHandler {

    private static Map<String, String> map = Maps.newHashMap();
    private static Map<String, String> sourceMap = Maps.newHashMap();

    static {
        //
        map.put("路面图像", "Images");
        map.put("景观图像", "ViewImages");
        //源路径下的子文件夹
        sourceMap.put("路面图像", "Images");
        sourceMap.put("景观图像", "");
    }

    @Override
    public String getType() {
        return "图像类数据";
    }


    /**
     * @param path 目标path  /.../图像类数据/
     * @param area 区县
     */
    @Override
    public void handleTypeData(String path, String area, Parameter parameter) {
        System.out.println("处理区县【" + area + "】的图像类数据");
        String baseSourcePath = parameter.getBaseSourcePath() + area + "\\";
        String sourceRoutePath = parameter.getBaseSourcePath() + "上下行库.txt";
        List<String> allRouteList = FileUtil.readLines(sourceRoutePath, "UTF-8");
        List<String> areaRouteList = allRouteList.stream().filter(r -> r.contains(area)).distinct()
                .map(r -> r.replaceAll(area, "").trim())
                .collect(Collectors.toList());
        //上下行库转成Map C003431102 C003431102B
        Map<String, String> upMap = new HashMap(16);
        //上下行库中是否存在两个方向的路线编码
        Map<String, Integer> twoDirectionsMap = new HashMap(16);
        areaRouteList.stream().forEach(routeCode -> {
            String substringed = routeCode.substring(0, routeCode.length() - 1);
            if (twoDirectionsMap.isEmpty()) {
                twoDirectionsMap.put(substringed, 1);
            } else {
                Integer integer = Optional.ofNullable(twoDirectionsMap.get(substringed)).orElse(0);
                twoDirectionsMap.put(substringed, integer == 0 ? integer : integer + 1);
            }
        });
        areaRouteList.stream().forEach(routeCode -> {
            upMap.put(routeCode, routeCode);//路线存在多个上下行
        });
        for (String sourceType : map.keySet()) {
            System.out.println("当前处理的是【" + area + "】的【" + sourceType + "】类型数据");
            //获取路线编码
            String sourcePath = baseSourcePath + sourceType + "\\";
            //xxx/area/路面图像(景观)/  +""(景观的路径)或者/images/(路面的路径)
            String sourceTimeFilePath = sourcePath + sourceMap.get(sourceType);
            File[] files = new File(sourceTimeFilePath).listFiles();
            if (files == null || files.length == 0) {
                throw new RuntimeException("未找到" + sourceTimeFilePath + "路径下的文件数据");
            }
            //File file = files[0];
            for (File file : files) {
                File[] routFiles = file.listFiles();
                if (routFiles == null || routFiles.length == 0) {
                    throw new RuntimeException("未找到" + file.getPath() + "路径下的路线数据");
                }
                for (File routFile : routFiles) {
                    System.out.println("开始处理路线【" + routFile.getName() + "】的【" + sourceType + "】数据");
                    //创建路线目录 /.../图像类数据/+路线编码
                    String sourceRouteName = routFile.getName();//获取到上下行中的路线编码带方向C515431102A
                    //目标文件夹
                    String targetRouteName = "";
                    // 上下行文件中不带方向的路线编码C515431102
                    String substring = sourceRouteName.substring(0, sourceRouteName.length() - 1).toUpperCase();
                    if (!upMap.isEmpty()) {
                        Integer integer = Optional.ofNullable(twoDirectionsMap.get(substring)).orElse(0);
                        if (integer > 1) {//路线编号存在多个上下行
                            targetRouteName = upMap.get(sourceRouteName);
                        } else {
                            targetRouteName = Optional.ofNullable(upMap.get(substring.concat("A"))).orElse(upMap.get(substring.concat("B")));
                        }
                    }
                    if(Objects.isNull(targetRouteName)){
                        continue;
                    }
                    //创建 D:\transform\零陵区\图像类数据\C515431102A 的文件夹就是上下行中的编号
                    String routeDir = Directory.createDirectory(path, targetRouteName, FileTypeEnum.DIRECTORY);
                    //创建文件类型目录Images(ViewImages) /.../图像类数据/路线编码+/Images(ViewImages)
                    String typeDirectory = Directory.createDirectory(routeDir, map.get(sourceType), FileTypeEnum.DIRECTORY);
                    //创建目标的日期文件夹，日期数据通过LBI文件夹里面的数据获取
                    String LBIPath = baseSourcePath + TransformConstant.LBI;
                    File timeFile = FileTransferUtil.getLBIFile(LBIPath, sourceRouteName);
                    String[] split = timeFile.getName().split("-");
                    String time = split[split.length - 1].split("\\.")[0];
                    //图像类数据\C063653127A\Images\20230714105000/
                    //创建日期文件夹 /.../图像类数据/路线编码+/Images(ViewImages)/日期
                    String targetPath = Directory.createDirectory(typeDirectory, time, FileTypeEnum.DIRECTORY);
                    //获取原路线的文件
                    String sourceRouteFilePath = file.getPath() + "\\" + sourceRouteName;
                    //获取该文件夹下面的所有文件
                    File[] sourceRouteFiles = new File(sourceRouteFilePath).listFiles();
                    if (sourceRouteFiles == null || sourceRouteFiles.length == 0) {
                        //复制原路径文件夹到目标路径
                        // FileUtil.copy(sourceRouteFilePath,targetPath,true);
                        //throw new RuntimeException("未找到"+sourceRouteFilePath+"路径下的文件数据");
                        continue;
                    }
                    Map<String, String> map = new HashMap<>();
                    for (File sourceRouteFile : sourceRouteFiles) {
                        if (sourceRouteFile.isDirectory()) {
                            List<File> sourceImgFiles = FileUtil.loopFiles(sourceRouteFile);
                            if (sourceImgFiles.size() > 5000) {
                                for (int i = 0; i < sourceImgFiles.size(); i++) {
                                    String folderName = getFileName(i, 5000);
                                    Directory.createDirectory(targetPath, folderName, FileTypeEnum.DIRECTORY);
                                    //文件夹

                                    FileUtil.copy(sourceImgFiles.get(i).getPath(), targetPath + "/" + folderName + "/" + sourceImgFiles.get(i).getName(), true);
                                    String fileName = sourceImgFiles.get(i).getName();
                                    map.put(fileName, folderName);
                                }

                            } else {
                                //索引下标文件夹直接复制
                                System.out.println("开始复制原路径【" + sourceRouteFile.getPath() + "】到目标路径:" + targetPath);
                                FileUtil.copy(sourceRouteFile.getPath(), targetPath, true);
                                System.out.println("复制原路径【" + sourceRouteFile.getPath() + "】到目标路径【" + targetPath + "】完成");
                            }
                            continue;
                        }
                        //文件内容修改
                        FileTransferUtil.fileIndexTransfer(sourceRouteFile, targetPath, map, upMap, targetRouteName);
                    }
                    System.out.println("区县【" + area + "】的【" + sourceType + "】的路线【" + sourceRouteName + "】文件数据处理完成");
                }
            }
            //日期下面是路线文件夹

            System.out.println("区县【" + area + "】的【" + sourceType + "】数据处理完成");
        }
        String sourceExceptionPath = baseSourcePath + "\\" + "异常路段照片";
        FileUtil.copy(sourceExceptionPath, path, true);

    }

    //根据传入数据生成文件夹名称
    public String getFileName(int index, int maxPage) {
        int i = Math.round(index / maxPage) + 1;
        if (0 < i && i < 10) {
            return "0" + i;
        }
        return i + "";
    }


    public static void main(String[] args) {
        String line = "C161431102A->0+000->01>K000+005_111.642911_26.262553.jpg";
        String s = line.split(">")[3];
        int i = s.indexOf("_");
        String modifiedLine = line.replaceAll("0\\+000->", s.substring(1, i) + "->");

        System.out.println(modifiedLine);
    }

}
